//
//  MyUtility.m
//  Graduate
//
//  Created by xp on 16/8/2.
//  Copyright © 2016年 mingthink. All rights reserved.
//

#import "MyUtility.h"
@implementation MyUtility

#pragma 取得当前系统时间戳
+(NSString *)getCurrentTimeStamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    // 获取时间戳
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    // 精确到小数点前
    NSString *timeStamp = [NSString stringWithFormat:@"%.0f", a];
    return timeStamp;
}
+(NSDate *)getCurrentDate
{
    NSDate *date=[NSDate date];
    NSTimeZone *timeZone=[NSTimeZone systemTimeZone];
    NSInteger interval=[timeZone secondsFromGMTForDate:date];
    NSDate *currentDate=[date dateByAddingTimeInterval:interval];
    return currentDate;
}

//判断是否为空
+(BOOL)isEmpty:(id)string{
    if (string == nil) {
        return YES;
    }
    if (string == NULL) {
        return YES;
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    
    if ([string isKindOfClass:[NSString class]] && [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
        return YES;
    }
    
    if ([string isKindOfClass:[NSArray class]]) {
        NSArray *ary =  string;
        if (ary.count < 1) return YES;
    }
    
    if ([string isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic =  string;
        if (dic.count < 1) return YES;
    }
    
    return false;
}


+ (NSString *)pinYinTransform:(NSString *)chinese{
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chinese mutableCopy];
    
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    DeLog(@"%@", pinyin);
    
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    DeLog(@"%@", pinyin);
    
    //返回最近结果
    return pinyin;
}

+ (NSString *)getDocumentDirectory{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPathStr = [paths objectAtIndex:0];
    return documentPathStr;
}

+(NSString*)getImageUrl:(NSString*)path{
    NSRange range   = [path rangeOfString:@"http://"];//判断字符串是否包含
    NSRange range2  = [path rangeOfString:@"https://"];
    //处理url中包含中文
    NSString *newPath = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)path,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    if (range.length >0 || range2.length > 0)//包含
    {
        return newPath;
    }
    else//不包含
    {
        //range = [_path rangeOfString:@"https://"];
        if (range.length >0)//包含
        {
            return newPath;
        } else {
            //NSString *strHost = [FuncPublic getIpHost];
            return [NSString stringWithFormat:@"%@/%@",API_HOST, newPath];
        }
    }
}
+(NSString*)checkURL:(NSString* )urlStr{
    if ([StringUtils isEmpty:urlStr]) {
        return urlStr;
    }
    
//    NSRange range   = [urlStr rangeOfString:@"http://"];//判断字符串是否包含
//    NSRange range2  = [urlStr rangeOfString:@"https://"];
    //处理url中包含中文
    NSString *newUrlStr = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)urlStr,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    if ([urlStr hasPrefix:@"http://"] || [urlStr hasPrefix:@"https://"])//包含
    {
        return newUrlStr;
    }
    else//不包含
    {
        if ([[newUrlStr substringToIndex:1] isEqualToString:@"/"]) {
             return [NSString stringWithFormat:@"%@%@",[[HostUtil sharedInstance] getWebHost], newUrlStr];
        }else{
            return [NSString stringWithFormat:@"%@/%@",[[HostUtil sharedInstance] getWebHost], newUrlStr];
        }
    }
}
+(void) printParams:(NSMutableDictionary*)params andURL:(NSString *)urlStr
{
    NSString *str ;
    if (params == nil || params.allKeys.count==0){
           str = [NSString stringWithFormat:@"%@",urlStr];
    }else{
            str = [NSString stringWithFormat:@"%@?",urlStr];
    }
    NSMutableArray *paramsArr=[[NSMutableArray alloc]init];
    for(NSString *key in params) {
        NSString *param = [params objectForKey:key];
        //MDLog(@"key=%@   value=%@",key,param);
        NSString *strParam = [NSString stringWithFormat:@"%@=%@",key,param];
        [paramsArr addObject:strParam];
    }
    str=[str stringByAppendingString:[paramsArr componentsJoinedByString:@"&"]];
    DeLog(@"-------apiRequestURL: %@",str);
    //string = [string1 stringByAppendingString:string2];
}
+(NSString *)dateFormatterWithDateString:(NSString *)dateStr
{
    NSString *dateFormatter=nil;
        if (dateStr.length > 0){
            NSDate *date = [NSDate mt_dateFromDateStr:dateStr withFormatter:@"yyyy-MM-dd HH:mm"];
            NSInteger times = [date mt_hoursBeforeDate:[NSDate date]];
            if (times == 0){
                NSInteger minus = [date mt_minutesBeforeDate:[NSDate date]];
                if (minus <= 0) {
                    dateFormatter = @"刚刚";
                }else{
                    dateFormatter = [NSString stringWithFormat:@"%ld分钟前",[date mt_minutesBeforeDate:[NSDate date]]];
                }
            }else if (times < 24){
               dateFormatter = [NSString stringWithFormat:@"%ld小时前",times];
            }else if (times < 48){
               dateFormatter = [NSString stringWithFormat:@"昨天"];
            }else if (times < 72){
               dateFormatter = [NSString stringWithFormat:@"前天"];
            }else{
              dateFormatter = [dateStr componentsSeparatedByString:@" "][0];
            }
        }
    return dateFormatter;

}
+(NSString *)getAppShortVersion
{
      NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    return version;
}
+(NSString *)getAppBuildVersion{
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    return version;
}
+(NSDictionary *)getParamsDictFromURL:(NSString *)urlStr{
    NSURL *url=[NSURL URLWithString:urlStr];
    NSString *paramStr=url.query;
    NSArray *array1=[paramStr componentsSeparatedByString:@"&"];
    NSMutableDictionary *paramDict=[[NSMutableDictionary alloc]init];
    for (NSString *str1 in array1) {
        NSArray *array2=[str1 componentsSeparatedByString:@"="];
        [paramDict setObject:array2[1] forKey:array2[0]];
    }
    return paramDict;
}
+ (NSString *)createIDFV
{
    NSString *idfvStr = [[UIDevice currentDevice].identifierForVendor UUIDString];
    NSString *md5Str=[MD5Util md5:idfvStr];
    return md5Str;
}

+ (NSString *)createUUID
{
    // Create universally unique identifier (object)
    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
    
    // Get the string representation of CFUUID object.
    NSString *uuidStr = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidObject));
    
    CFRelease(uuidObject);
    
    return uuidStr;
}
+(NSString *)getDvid
{
    CFUUIDRef puuid = CFUUIDCreate( nil );
    
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    
    CFRelease(puuid);
    
    CFRelease(uuidString);
    
    return result;
}
+(NSData *)uncompressZippedData:(NSData *)compressedData
{
    if ([compressedData length] == 0) return compressedData;
    
    unsigned full_length = [compressedData length];
    
    unsigned half_length = [compressedData length] / 2;
    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;
    z_stream strm;
    strm.next_in = (Bytef *)[compressedData bytes];
    strm.avail_in = [compressedData length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;
    while (!done) {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length]) {
            [decompressed increaseLengthBy: half_length];
        }
        // chadeltu 加了(Bytef *)
        strm.next_out = (Bytef *)[decompressed mutableBytes] + strm.total_out;
        strm.avail_out = [decompressed length] - strm.total_out;
        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) {
            done = YES;
        } else if (status != Z_OK) {
            break;
        }
    }
    if (inflateEnd (&strm) != Z_OK) return nil;
    // Set real length.
    if (done) {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    } else {
        return nil;
    }
}
@end
